/**
 * All rights Reserved, Designed By OprCalf
 * Copyright:    Copyright(C) 2016-2020
 * Company       OprCalf Ltd.
 */

package com.platform.gateway.common.exception;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.alibaba.fastjson.JSONObject;
import com.platform.gateway.common.message.ResponseMsg;
import com.platform.gateway.common.utils.MsgUtils;

/**
 * @projectName:  widget-api-spring-boot-starter
 * @package:      com.widget.exception
 * @className:    CommonExceptionHandler.java
 * @description:  统一异常处理
 * @author:       OprCalf
 * @date:         2018年12月24日
 */
@RestControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResponseMsg<Object> commonErrorHandler(HttpServletResponse resp, Exception e) throws Exception {
        System.out.println("进入到异常测试");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.setContentType("application/json;charset=UTF-8");
        ResponseMsg<Object> msg = new ResponseMsg<>();

        if (e instanceof CommonRuntimeException) {
            // 普通的异常拦截
            final CommonRuntimeException common = (CommonRuntimeException) e;
            msg = MsgUtils.buildFailureMsg(common.getMessage());

        } else if (e instanceof MethodArgumentNotValidException) {
            // 采用javax校验接口入参的拦截组装
            final MethodArgumentNotValidException valid = (MethodArgumentNotValidException) e;
            msg = MsgUtils.buildFailureMsg(buildParamError(valid.getBindingResult()));
        } else {
            // 其他不知道的异常拦截
            msg = MsgUtils.buildFailureMsg(e.getLocalizedMessage());
        }
        return msg;
    }

    /**
     * 构建参数错误
     * @author OprCalf
     * @date 2018年12月16日
     * @param result
     * @return JSONObject
     */
    private JSONObject buildParamError(BindingResult result) {
        JSONObject json = null;
        if (result.hasErrors()) {
            json = new JSONObject();
            final List<FieldError> errors = result.getFieldErrors();
            for (final FieldError error : errors) {
                json.put(error.getField(), error.getDefaultMessage());
            }
        }
        return json;
    }
}
